package com.rocky.project.action.model;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.LinkedList;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.DynaBean;
import org.hibernate.Session;

import com.opensymphony.webwork.ServletActionContext;
import com.rocky.project.action.base.BaseAction;
import com.rocky.project.model.admin.Resource;
import com.rocky.project.util.WebUtil;

public class ResourceAction extends BaseAction {
	private static final long serialVersionUID = -3510474656970657392L;

	@SuppressWarnings("unchecked")
	public String genResourceTree() throws Exception {
		if (this.from == null || this.from.equals("")) {
			this.from = "action";
		}
		String fromFile = WebUtil.getParaValue("fromFile");
		java.util.List<Object> values = new LinkedList<Object>();
		String queryHql = "SELECT distinct m.NSName  FROM Resource m WHERE m.deleted = false  and m.parent is null  and m.status <> 'deprecated' and m.active=true";
		// condition 1
		queryHql += "  and m.resourceType=?   ";
		values.add(this.from);
		// condition 2
		if (fromFile != null && !fromFile.equals("")) {
			queryHql += "  and m.fromFile=?   ";
			values.add(fromFile);
		}
		// queryHql += " order by m.showindex asc ";
		pageRecords = baseService.executeHqlWithParam(queryHql, values.toArray(), 0, null);
		return this.from;
	}
	
	@SuppressWarnings("unchecked")
	public String createResourceMenu() throws Exception{		
		
		String appContextPath = ServletActionContext.getRequest().getContextPath();
		Session session = baseService.getHibernateTemplate().getSessionFactory().openSession();    		
		session.createQuery("update Resource as r set r.status = 'deprecated' where r.resourceType='menu' and r.contextPath = '"+appContextPath+"' ").executeUpdate();
		
		String filename = WebUtil.getParaValue("filename");
		if(filename==null || filename.equals("") ){
			createResourceMenuFromFilename("/js/resourcemenu_admin.js", appContextPath);	
//			createResourceMenuFromFilename("/admin/menu_memberadmin.js", appContextPath);	
//			createResourceMenuFromFilename("/admin/menu_memberperson.js", appContextPath);
			
		}
//		filename = "/admin/menu_admin.js";
		return ajaxResult;
	}
	
	@SuppressWarnings("unchecked")
	private void createResourceMenuFromFilename( String filename, String appContextPath) throws UnsupportedEncodingException, IOException {
		StringBuffer jsonstr = new StringBuffer("");
		InputStream inputStream = ServletActionContext.getServletContext().getResourceAsStream(filename); 
		InputStreamReader ir = new InputStreamReader(inputStream,"utf-8");
		int c = ir.read();
		while(c!=-1){
			jsonstr.append((char) c );
			c = ir.read();
		}
		ir.close();		
		JSONObject object = JSONObject.fromObject(jsonstr.toString(),this.jsonConfig);
		if(object.isNullObject() || object.isEmpty()){
			throw new RuntimeException(" JSONObject.fromObject(jsonstr.toString()) occor error!");
		}
		DynaBean dynaBean =  (DynaBean) JSONObject.toBean(object);		
		Collection<DynaBean> dynaBeans = (Collection<DynaBean> )dynaBean.get("data");
		for(DynaBean each:dynaBeans){
			createResourceMenu(filename, each,null, appContextPath);
		}
	}
	@SuppressWarnings("unchecked")
	private void createResourceMenu(String filename, DynaBean each,Resource parent,String appContextPath) {
		Resource resource = null;
		Collection pageRecords = null;
		String text = (String)each.get("text");
		String module ="";
		String showindex = "999999999";
		try {
			 module = (String) each.get("module");
		} catch (Exception e) {
			log.info("module = (String) each.get(\"module\"); ");
		}
		try {
			 showindex = (String) each.get("showindex"); 
		} catch (Exception e) {
			log.info("showindex = (String) each.get(\"showindex\"); ");
		}		
		pageRecords = baseService.executeHqlNoParam("SELECT m FROM Resource AS m WHERE m.resourceType='menu' and  m.name = '"+text+"'  and m.fromFile='"+filename+"'", 0, null);
		if(pageRecords!=null&& !pageRecords.isEmpty()){
			resource=(Resource) pageRecords.iterator().next();
			resource.setShowindex(Integer.valueOf(showindex));
			resource.setContextPath(appContextPath);
			resource.setActionUrl((module==null&&module.equals("")?"":module));
			resource.setName(text);	        		
			resource.setNamespace(filename);
			resource.setNSName(filename);
			resource.setFromFile(filename);			
			resource.setStatus("old");
			if(parent!=null){
				resource.setParent(parent);
			}
			WebUtil.init4modify(resource);
			baseService.update(resource);
		}else{
			resource= new Resource();
			resource.setShowindex(Integer.valueOf(showindex));
			resource.setActionUrl((module==null&&module.equals("")?"":module));
			resource.setContextPath(appContextPath);
			resource.setName(text);	        		
			resource.setNamespace(filename);
			resource.setNSName(filename);
			resource.setFromFile(filename);
			if(parent!=null){
				resource.setParent(parent);
			}			        		
			resource.setStatus("new");	    
			resource.setResourceType("menu");	
			WebUtil.init4create(resource);
			baseService.create(resource);			
		}
		try {
			DynaBean beanChild = (DynaBean)each.get("menu");			
			if(beanChild!=null){
				Collection<DynaBean> dynaBeans2 = (Collection<DynaBean> )(beanChild.get("items"));			
				for(DynaBean each2:dynaBeans2){
					createResourceMenu(filename, each2,resource,appContextPath);
				}			
			}			
		} catch (Exception e) {
			log.info("no items exists,the leaf munu item.");
		}
	}	
	
	@SuppressWarnings("unchecked")
	public String readActionByNS()throws Exception {
		
		String resourceType = WebUtil.getParaValue("resourceType");	
		if(resourceType==null||resourceType.equals("")){
			resourceType="action";
		}
		String NSName = WebUtil.getParaValue("NSName");
		
		java.util.List<Object> paramsvalues = new LinkedList<Object>();		
		String queryHql = "SELECT  m  FROM Resource m WHERE m.deleted = false and m.status <> 'deprecated' and m.active=true   ";	
		
		queryHql += "   and m.resourceType= ?    ";
		paramsvalues.add(resourceType);
		

		if(NSName!=null && ! NSName.equals("")){
			queryHql += "	and m.parent is null  and m.NSName='"+NSName+"'    ";
		}else{ 
			queryHql +="	and m.parent.id='"+Long.valueOf(this.id)+"'";
		}	
		

		queryHql += "  order by m.showindex asc   ";
		
		this.pageRecords = null;
		this.pageRecords = baseService.executeHqlWithParam(queryHql,paramsvalues.toArray(),0, null);

		return SUCCESS;
	}

}